package com.cherry.example.network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//群聊的接收端
public class ChatReceiver extends Thread {
	
	@Override
	public void run() {
		try {
			//第一步： 创建udp接收端服务
			DatagramSocket socket = new DatagramSocket(9090);
			//第二步： 准备空的数据包，接收数据
			byte[] buf   = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			//第三步： 接收数据
			boolean flag = true;
			while(flag){
				socket.receive(packet); //packet.getAddress() 获取发送人的id地址。
				System.out.println(packet.getAddress().getHostAddress()+"说："+new String(buf,0,packet.getLength()));
			}
			
			//关闭资源
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
